#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <event.h>
#include <assert.h>

void read_cb(int fd, short event, void* arg) {
    char buf[1024];
    struct event* ev = (struct event *)arg;
    int res = read(fd, buf, sizeof buf);
    if (res > 0 && (event & EV_READ))
        printf("received data: %s %d\n", buf, res);
    else {
        printf("pipe closed or pipe error!\n");
        exit(0);
    }
}

int main() {
    // 创建一个管道
    mkfifo("myfifo", 0664);
    int fd = open("myfifo", O_RDONLY);
    assert(fd != -1);
    // 创建一个reactor监听
    struct event_base* evbase = event_base_new();
    // 创建事件
    struct event* ev = event_new(evbase, fd, EV_READ | EV_PERSIST, read_cb, (void *)ev);
    // 添加事件
    event_add(ev, NULL);
    // 开始监听
    event_base_dispatch(evbase);
    // 释放资源
    event_free(ev);
    event_base_free(evbase);

    return 0;
}